<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button class="btn">发送消息</button>
  <button class="btn2">关闭连接</button>
  <script>
    // 1.建立连接
    const ws = new WebSocket('wss://javascript.info/article/websocket/demo/hello')
    // 2.监听连接成功
    ws.onopen = () => {
      console.log('连接成功')
    }
    // 3.发消息
    document.querySelector('.btn').addEventListener('click', () => {
      ws.send('你好，websocket 服务器')
    })
    // 4.接受消息
    ws.onmessage = evt => console.log('服务端发的消息', evt);
    // 5.关闭连接
    // ws.close()
    document.querySelector('.btn2').addEventListener('click',()=>{
      ws.close()
    })
    // 6.监听关闭连接
    ws.onclose = () => {
      console.log('连接关闭');
    }
  </script>
</body>

</html>